package org.lzy.shop.util

import android.app.Application
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.graphics.toColorInt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import kotlin.coroutines.CoroutineContext

/**
 * 自定义Toast工具类
 * 成功消息显示绿色背景，错误消息显示红色背景
 */
object ToastUtil : CoroutineScope {
    // 实现CoroutineScope接口，用于管理协程生命周期
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main

    // 主协程作用域，用于在主线程上执行UI操作
    private val mainScope = MainScope()
    // 使用WeakReference避免内存泄漏
    private var contextRef: WeakReference<Context>? = null
    private var mToast: Toast? = null
    private  val COLOR_SUCCESS = "#4CAF50".toColorInt()
    private  val COLOR_ERROR = "#F44336".toColorInt()
    private  val COLOR_DEFAULT = "#333333".toColorInt()
    private  val TEXT_COLOR = Color.WHITE

    private const val TOAST_PADDING_HORIZONTAL = 40 // 水平内边距
    private const val TOAST_PADDING_VERTICAL = 10  // 垂直内边距
    private const val TOAST_TEXT_SIZE = 14f        // 文字大小

    private const val TOAST_CORNER_RADIUS =60f    // 圆角半径

    private const val TOAST_DURATION_SHORT = 2000L // 短时间显示（毫秒）
    private const val TOAST_DURATION_LONG = 3500L  // 长时间显示（毫秒）

    /**
     * 初始化ToastUtil，应在Application中调用
     */
    fun init(application: Application) {
        // 只保存Application Context，并使用弱引用
        contextRef = WeakReference(application.applicationContext)
    }

    /**
     * 清理资源，建议在Application的onTerminate中调用
     */
    fun release() {
        mainScope.cancel()
        cancelToast()
        contextRef?.clear()
        contextRef = null
    }

    /**
     * 取消当前显示的Toast
     */
    private fun cancelToast() {
        mToast?.cancel()
        mToast = null
    }

    /**
     * 为视图设置圆角背景
     */
    private fun setRoundedBackground(view: View, backgroundColor: Int) {
        // 创建圆角矩形背景
        val drawable = GradientDrawable()
        drawable.shape = GradientDrawable.RECTANGLE
        drawable.setColor(backgroundColor)
        drawable.cornerRadius = TOAST_CORNER_RADIUS

        // 应用背景
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            view.background = drawable
        } else {
            // 兼容旧版本
            @Suppress("DEPRECATION")
            view.setBackgroundDrawable(drawable)
        }
    }

    /**
     * 显示默认Toast
     */
    fun show(message: String?, duration: Long = TOAST_DURATION_SHORT) {
        if (message.isNullOrEmpty()) return
        showToastWithCoroutine(message, COLOR_DEFAULT, duration)
    }

    /**
     * 显示成功Toast（绿色背景）
     */
    fun showSuccess(message: String?, duration: Long = TOAST_DURATION_SHORT) {
        if (message.isNullOrEmpty()) return
        showToastWithCoroutine(message, COLOR_SUCCESS, duration)
    }

    /**
     * 显示错误Toast（红色背景）
     */
    fun showError(message: String?, duration: Long = TOAST_DURATION_SHORT) {
        if (message.isNullOrEmpty()) return
        showToastWithCoroutine(message, COLOR_ERROR, duration)
    }

    /**
     * 显示警告Toast（黄色背景）
     */
    fun showWarning(message: String?, duration: Long = TOAST_DURATION_SHORT) {
        if (message.isNullOrEmpty()) return
        showToastWithCoroutine(message, Color.parseColor("#FF9800"), duration)
    }


    /**
     * 使用协程显示自定义Toast
     */
    private fun showToastWithCoroutine(message: String, backgroundColor: Int, duration: Long) {
        // 取消之前的Toast
        cancelToast()

        // 立即显示新Toast
        showCustomToast(message, backgroundColor)

        // 使用协程在指定时间后自动取消Toast
        mainScope.launch {
            delay(duration)
            cancelToast()
        }
    }
    /**
     * 显示自定义颜色背景的Toast
     */
    private fun showCustomToast(message: String, backgroundColor: Int) {
        // 从弱引用中获取Context
        val context = contextRef?.get() ?: return

        try {
            mToast = Toast(context).apply {
                // 设置居中显示
                setGravity(Gravity.CENTER, 0, 0)

                // 设置自定义视图
                val inflater = LayoutInflater.from(context)
                val view = inflater.inflate(android.R.layout.simple_list_item_1, null)
                val textView = view.findViewById<TextView>(android.R.id.text1)

                // 设置文字和样式
                textView.text = message
                textView.setTextColor(TEXT_COLOR)
                textView.textSize = TOAST_TEXT_SIZE
                textView.setPadding(TOAST_PADDING_HORIZONTAL, TOAST_PADDING_VERTICAL,
                    TOAST_PADDING_HORIZONTAL, TOAST_PADDING_VERTICAL)
                textView.gravity = Gravity.CENTER

                // 设置圆角背景
                setRoundedBackground(view, backgroundColor)

                // 仅在支持的版本设置阴影
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    view.elevation = 6f // 稍微增加阴影效果
                }

                // 设置Toast的视图
                this.view = view
            }
            // 显示Toast
            mToast?.show()
        } catch (e: Exception) {
            // 捕获可能的异常，避免Toast显示失败导致应用崩溃
            e.printStackTrace()
            // 降级处理：使用系统默认Toast
            try {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
            } catch (innerE: Exception) {
                // 防止降级方案也失败
                innerE.printStackTrace()
            }
        }
    }

}
